# -*- coding:utf-8 -*-

"""
描述：
Created on 2016/11/26
@author: Line
"""

import sys

reload(sys)
sys.setdefaultencoding('utf-8')

import os
from xml.etree import ElementTree
from PIL import Image
import json

import logging  # 引入logging模块

logging.basicConfig(level=logging.DEBUG)  # 设置日志级别
logger = logging.getLogger(__file__)


def tree_to_dict(tree):
    d = {}
    for index, item in enumerate(tree):
        if item.tag == 'key':
            if tree[index + 1].tag == 'string':
                d[item.text] = tree[index + 1].text
            elif tree[index + 1].tag == 'true':
                d[item.text] = True
            elif tree[index + 1].tag == 'false':
                d[item.text] = False
            elif tree[index + 1].tag == 'dict':
                d[item.text] = tree_to_dict(tree[index + 1])
    return d


def to_list(x):
    l = x.replace('{', '').replace('}', '').split(',')
    t = []
    for i in l:
        t.append(int(i))
    return t


def gen_png_from_plist(plist_filename, png_filename):
    logger.info("plist_filename:[%s],png_filename:[%s]" % (plist_filename, png_filename,))
    file_path = plist_filename.replace('.plist', '')
    logger.info("file_path:[%s]" % (file_path,))
    big_image = Image.open(png_filename)
    root = ElementTree.fromstring(open(plist_filename, 'r').read())
    plist_dict = tree_to_dict(root[0])
    if not plist_dict.get('frames'):
        logger.info("plist_filename not has frames:%s, " % (plist_filename,))
        return

    for k, v in plist_dict['frames'].items():
        logger.info("k:%s,v:%s" % (k, v))
        if not v.get('frame'):
            logger.info("plist_filename not  frame:%s, " % (plist_filename,))
            return

        frameBox = to_list(v['frame'])
        sourceColorRect = to_list(v['sourceColorRect'])
        sourceSize = to_list(v['sourceSize'])
        offset = to_list(v['offset'])
        rotated = v['rotated']  # 是否旋转

        # 大图上的需要剪切的区域
        clipX = int(frameBox[0])
        clipY = int(frameBox[1])
        width = int(frameBox[2])
        height = int(frameBox[3])

        resultImg = Image.new('RGBA', sourceSize, (0, 0, 0, 0))
        logger.info("create new empty image:%s" % (sourceSize,))
        if rotated:
            clipBox = (clipX, clipY, clipX + height, clipY + width)
            clipBoxImg = big_image.crop(clipBox)
            clipBoxImg = clipBoxImg.rotate(90, expand=True)
            result_box = (abs(offset[0]), abs(offset[1]), width, height)
            resultImg.paste(clipBoxImg, tuple(result_box), mask=0)
        else:
            clipBox = (clipX, clipY, clipX + width, clipY + height)
            clipBoxImg = big_image.crop(clipBox)
            result_box = (abs(offset[0]), abs(offset[1]), width, height)
            resultImg.paste(clipBoxImg, tuple(result_box), mask=0)

        # outfile = file_path + '\\' + k
        # outfile = outfile.replace("/", "\\")
        # lastPath = os.path.dirname(outfile)
        outfile = os.path.join(file_path, k)
        lastPath = os.path.dirname(outfile)
        logger.info("lastPath:[%s],outfile[%s]" % (lastPath, outfile))
        if not os.path.exists(lastPath):
            os.makedirs(lastPath)

        logger.info("generated: %s" % (outfile,))
        if resultImg:
            resultImg.save(outfile)


def unpak_a_file(filename):
    plist_filename = filename + '.plist'
    png_filename = filename + '.png'
    logger.info(u"处理文件[%s],[%s]" % (plist_filename, png_filename))
    if os.path.exists(plist_filename) and os.path.exists(png_filename):
        gen_png_from_plist(plist_filename, png_filename)
    else:
        logger.warn(u"处理文件[%s]和[%s]不存在" % (plist_filename, png_filename))
    pass


def unpak_dir_file(path):
    for dirpath, dirs, files in os.walk(path):
        for file in files:
            abs_path = os.path.join(dirpath, file)
            postfix = os.path.splitext(abs_path)[1]
            logger.info(abs_path)
            if postfix == ".plist":
                a_len = len(".plist")
                png_filename = abs_path[:-a_len]
                unpak_a_file(png_filename)


def gen_png_from_json(json_filename, png_filename):
    logger.info("json_filename:[%s],png_filename:[%s]" % (json_filename, png_filename,))
    file_path = json_filename.replace('.json', '')
    logger.info("file_path:[%s]" % (file_path,))
    big_image = Image.open(png_filename)

    fd = open(json_filename)
    content = fd.read()
    data = json.loads(content)
    fd.close()

    framList = data.get("res")
    for name, rectData in framList.items():
        clipX = rectData["x"]
        clipY = rectData["y"]
        width = rectData["w"]
        height = rectData["h"]

        sourceSize = [width, height]
        resultImg = Image.new('RGBA', [width, height], (0, 0, 0, 0))
        logger.info("create new empty image:%s" % (sourceSize,))

        clipBox = (clipX, clipY, clipX + width, clipY + height)
        clipBoxImg = big_image.crop(clipBox)
        result_box = (0, 0, width, height)
        resultImg.paste(clipBoxImg, tuple(result_box), mask=0)

        outfile = os.path.join(file_path, "%s.png" % (name,))
        lastPath = os.path.dirname(outfile)
        logger.info("lastPath:[%s],outfile[%s]" % (lastPath, outfile))
        if not os.path.exists(lastPath):
            os.makedirs(lastPath)

        logger.info("generated: %s" % (outfile,))
        if resultImg:
            resultImg.save(outfile)


def unpak_json_file(filename):
    plist_filename = filename + '.json'
    png_filename = filename + '.png'
    if os.path.exists(plist_filename) and os.path.exists(png_filename):
        gen_png_from_json(plist_filename, png_filename)
    else:
        logger.info("make sure you have both json and png files in the same directory:[%s]\n[%s]" % (plist_filename, png_filename))
    pass


def unpak_json_files(path):
    for dirpath, dirs, files in os.walk(path):
        for file in files:
            abs_path = os.path.join(dirpath, file)
            postfix = os.path.splitext(abs_path)[1]
            if postfix == ".json":
                a_len = len(".json")
                png_filename = abs_path[:-a_len]
                unpak_json_file(png_filename)


if __name__ == '__main__':
    # filename = sys.argv[1]
    # unpak_dir_file("D:\\tmp\\jiejiyouxting\\res")
    # unpak_json_files("/Users/bolin/data/tmp/hunter_fish/fish")
    unpak_dir_file(u"G:\\房卡游戏包\\csmj")
    pass